package com.coder.rental.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.coder.rental.entity.*;
import com.coder.rental.mapper.RoleMapper;
import com.coder.rental.mapper.RolePermissionMapper;
import com.coder.rental.mapper.UserMapper;
import com.coder.rental.mapper.UserRoleMapper;
import com.coder.rental.service.IRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 权限_角色管理 服务实现类
 * </p>
 *
 * @author zhaojj
 * @since 2025-01-10
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {
    @Resource
    private UserMapper userMapper;
    @Resource
    private UserRoleMapper userRoleMapper;
    @Resource
    private RolePermissionMapper rolePermissionMapper;

    @Override
    public Page<Role> selectList(Page<Role> page, Role role) {
        // 创建查询条件
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StrUtil.isNotEmpty(role.getRoleName()), "role_name", role.getRoleName());
        queryWrapper.orderByAsc("create_time");
        // 查询创建者id
        Integer userId = role.getCreaterId();
        // 根据id 查询用户信息
        User user = userMapper.selectById(userId);
        // 如果用户不是管理员，则只能查询自己的角色
        if( user!= null && user.getIsAdmin() != 1){ // 1 是管理员
            queryWrapper.eq("creater_id",userId);
        }
        return baseMapper.selectPage(page, queryWrapper);
    }

    @Override
    public boolean hasUser(Integer id) {
        QueryWrapper<UserRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("role_id", id);
        return userRoleMapper.selectCount(queryWrapper) > 0;
    }

    @Override
    public boolean delete(String ids) {
        List<Integer> list = Arrays.stream(ids.split(","))
                .map(Integer::parseInt)
                .toList();
        if(!list.isEmpty()){
            for (Integer id : list) {
                if (!hasUser(id)) {
                    rolePermissionMapper.delete(new QueryWrapper<RolePermission>().eq("role_id", id));
                    baseMapper.deleteById(id);
                }
            }
        }
        return true;
    }

    @Override
    public boolean assignPermission(Integer roleId, List<Integer> permissionIds) {
        // 把原来关联的权限先清除
        QueryWrapper<RolePermission> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("role_id", roleId);
        rolePermissionMapper.delete(queryWrapper);
        // 插入新的数据
        try {
            if (permissionIds!= null&& !permissionIds.isEmpty()){
                for(Integer permissionId : permissionIds){
                    RolePermission rolePermission = new RolePermission();
                    rolePermission.setRoleId(roleId);
                    rolePermission.setPermissionId(permissionId);
                    rolePermissionMapper.insert(rolePermission);
                }
            }
        }catch (Exception e){
            //throw new RuntimeException("分配权限失败");
            return false;
        }
        return true;
    }

    @Override
    public List<Integer> selectRoleIdByUserId(Integer userId) {
        return baseMapper.selectRoleIdByUserId(userId);
    }
}
